package org.sucri.floxs.utils;

import org.sucri.floxs.Tools;
import org.sucri.floxs.ext.JsFunction;
import org.sucri.floxs.ext.JsonConfig;
import org.sucri.floxs.ext.widget.Column;

import java.util.Map;
import java.util.List;
import java.util.ArrayList;

/**
 * Created by IntelliJ IDEA.
 * User: Wen Yu
 * Date: Aug 15, 2007
 * Time: 11:39:51 PM
 * To change this template use File | Settings | File Templates.
 */
public class Json_Util
{
  private static boolean mDebug = true;
  private static String mSpacer = "  ";


  public boolean isDebug()          { return mDebug; }
  public void    isDebug(boolean s) { mDebug = s; }

  public static String br() { return mDebug ? "\n" : ""; }
  public static String br(int indent)
  {
    return mDebug ? "\n" + Tools.spacer(mSpacer, indent) : "";
  }

  public static <T extends JsonConfig> String toJSONString(List<T> s, int indent)
  {
    List<Map<String , Object>> props = new ArrayList<Map<String, Object>>();
    for (T c : s)
    {
      props.add(c.getProperties());
    }
    return doJSONString(props, indent);
  }
  private static String doJSONString(List<Map<String, Object>> s, int indent)
  {
    String js = null;
    if (Tools.good(s))
    {
      for (Map<String, Object> m : s)
      {
        js = Tools.extend(js, toJSONString(m, indent), ",");
      }
    }
    return "[" + js + "]";

  }
  public static String toJSONString(Map<String, Object> s)
  {
    return toJSONString(s, 0);
  }
  public static String toJSONString(Map<String, Object> s, int indent)
  {
    indent++;
    String js = null;
    if (Tools.good(s))
    {
      for (String k : s.keySet())
      {
        js = Tools.extend(js, k + ":" + toJSONString(k, s.get(k), indent), "," + br(indent+1));
      }
    }
    return "{" + br(indent) + js + br(indent) + "}";
  }
  public static String toJSONString(String k, Object v, int indent)
  {
    if (v instanceof List)
    {
      try
      {
        return toJSONString((List<JsonConfig> )v, indent);
      }
      catch (Exception e) {e.printStackTrace();}
    }
    return (Tools.isNumber( v) ||
            Tools.isBoolean(v) ||
            v instanceof JsFunction) ? v + "" : "'" + v + "'";
  }
  public static String callJs(String objname, String method, String ... args)
  {
    return (Tools.good(objname) ? objname + "." : "") + method + "(" + br() + Tools.toString(args, ",") + br() + ")";
  }
  public static String newJs(String name, String ... args)
  {
    return "new " + name + "(" + Json_Util.br() + Tools.toString(args, ",") + Json_Util.br() + ")";    
  }
  public static String funcJs(String codes)
  {
    return "function() {" + br() + codes + br() + "}";
  }
  public static String ifJs(String condi, String _if, String _else)
  {
    return "if (" + condi + ") {" + br() + _if + br() + "}" + (Tools.good(_else) ? " else {" + _else + "}" : "");    
  }
}
